#/usr/bin/perl                                                                                                                           
use POSIX "fmod"; # float modulus
use List::Util qw[min]; # min function

# Do simulation results file globbing
$outputdir = "/home/rumen/simulation1";
#$query = "K=0_P=0.25_MU=1e-06_NU=1e-05_RSM=1_B=0.02_D=0.016_NN=100_T=7300_H=300_W=300";
$query = "NU=1e-04";
#$query = "P=1_MU=1e-08_NU=1e-05";

# Get all sweeps that match the query
opendir(DIR, $outputdir);
@files = grep { /$query/ } readdir(DIR);
closedir(DIR);

foreach $f (@files) {
    print STDERR "Processing sweep $f...\n";
    $dir = $outputdir."/".$f;    
    opendir(DIR, $dir);    
    @infiles = grep { /rep(\d+)\.log/ } readdir(DIR);
    closedir(DIR);
    
    # Contains all the rep runs number, e.g. if rep45, rep3, rep1 are present, rephash stores 45, 3, 1
    my %rephash = ();   
    foreach $i (@infiles) {
	@repnumber = split (/rep|\./, $i);
	$rephash{$repnumber[1]}=1;
    }

    foreach $run (sort {$a <=> $b} keys %rephash){
	# The name of the run:
	$command = "R CMD BATCH --vanilla --slave '--args runfolder=\"$dir\" run=\"$run\"' automated.plotting.grid.landscape.neutral.R ";
	print $command."\n";
	system($command);

    }
}
